from selenium import webdriver
import conf
import time
from selenium.webdriver.support.wait import WebDriverWait
from douyin_download.get_douyin_cookie import get_douyin_cookies
import os
import logging
import json
import asyncio

'创建一个webdriver类，并设置cookie'
class InsWebdriver:
    def __init__(self):
        '''
        初始化浏览器，并进行浏览器设置等操作，继承该类都会获取该属性
        '''
        self.driver = webdriver.Chrome()
        self.driver.maximize_window()
        self.wait = WebDriverWait(self.driver, timeout=10)
    def set_douyin_cookie(self,target_url:str = 'https://creator.douyin.com/'):
        cookie_fload_filepath = conf.douyin_upload_cookie_fload_path
        file_name='douyin_creator_cookie.json'
        file_path = conf.douyin_upload_cookie_file_path
        if os.path.isfile(file_path):
            logging.info('cookie文件不存在，请在新窗口登录后获取')

            '''
            异步等待获取cookie方法执行完成以后再执行访问
            '''
            get_douyin_cookies()
        self.driver.get(target_url)
        with open(file_path,'r') as f:
            cookies_json = json.load(f)
        for cookie in cookies_json:
            self.driver.add_cookie(cookie)
        self.driver.refresh()

        js_path = conf.JS_PATH
        with open(js_path, 'r') as f:
            js = f.read()
            self.driver.execute_script(script=js)

        time.sleep(10)

if __name__ == '__main__':
    InsWebdriver().set_douyin_cookie()
